package com.fishv.fishvdianping.common;

import cn.hutool.core.bean.BeanUtil;
import com.fishv.fishvdianping.model.vo.UserVO;
import jodd.util.StringUtil;
import lombok.Data;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author yuwei
 * @date 18:45 2024/10/20
 */
@Data
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if(StringUtil.isNotBlank(token)){
            //得到用户
            Map<Object,Object> userMap = stringRedisTemplate.opsForHash().entries(token);
            if(userMap != null && userMap.size() > 0){
                UserVO userVO = BeanUtil.fillBeanWithMap(userMap, new UserVO(), true);
                UserHolder.saveUser(userVO);
                //刷新时间
                stringRedisTemplate.expire(token,30, TimeUnit.MINUTES);
            }


        }
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
